package com.example.administrator.activitydemo;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private ListView mListView;
    //从幕课网上请求的json网址
    private static String URL = "http://www.imooc.com/api/teacher?type=4&num=30";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mListView = (ListView) findViewById(R.id.lv_main);
        new NewsAsyncTask().execute(URL);

    }


    /**
     * 实现网络的异步访问，不要忘记在获取数据后手动添加Execute方法
     */
    class NewsAsyncTask extends AsyncTask<String ,Void,List<NewsBean>>{

        @Override
        protected List<NewsBean> doInBackground(String... params) {
            return getJsonData(params[0]);
        }

        @Override
        protected void onPostExecute(List<NewsBean> newsBeans) {
            super.onPostExecute(newsBeans);
            //将生成的newsBeans设置给我们的ListView
            NewsAdapter adapter = new NewsAdapter(MainActivity.this,newsBeans,mListView);
            mListView.setAdapter(adapter);
        }
    }

    /**
     * 将url对应的JSON格式数据转化为我们所封装的NewsBean
     * @param url
     * @return
     */
    private List<NewsBean> getJsonData(String url) {
        List<NewsBean> newsBeanList = new ArrayList<>();
        try {
            URL isUrl = new URL(url);
            InputStream is = isUrl.openStream();
            String jsonString = readStream(is);//调用自己写的读取流的方法

            JSONObject jsonObject;
            NewsBean newsBean;
            jsonObject = new JSONObject(jsonString);
            JSONArray jsonArray = jsonObject.getJSONArray("data");//取出json[arr]中的data
            for(int i =0;i<jsonArray.length();i++){
                jsonObject = jsonArray.getJSONObject(i);//取出每个jsonObject
                newsBean = new NewsBean();
                newsBean.newsIconUrl = jsonObject.getString("picSmall");//取出data中图片路径标签
                newsBean.newsTitle = jsonObject.getString("name");//取出data中图片title
                newsBean.newsContent = jsonObject.getString("description");//取出data中图片title
                newsBeanList.add(newsBean);
            }


        }catch (Exception e){
            e.printStackTrace();
        }
        return newsBeanList;
    }

    /**
     * 通过is解析网页返回的数据
     * @param is
     * @return
     */
    private String readStream(InputStream is){
        InputStreamReader isr;
        String result = "";
        try {
            String line = "";
            isr = new InputStreamReader(is,"utf-8");
            BufferedReader br = new BufferedReader(isr);
            while ((line=br.readLine())!=null){
                result +=line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }
}
